<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/hexo/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/hexo/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/hexo/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/hexo/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/hexo/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/hexo/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/hexo/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="开发笔记,">










<meta name="description" content="终于聊回正事儿了，哈哈，今天聊聊jwt，概念性的东西，我还是不多说了，每个人肯定都有自己的认识，大家想深入了解的，自己去Google，去百度吧~咱们就直接看东西了先说一下jwt的官网：https://jwt.io/，集成开发的时候也是要到这里下载一下jwt的开发包，如果是.net 的话，建议直接用nuget包来管理；所谓jwt就是json web token的简称，所以，几乎支持市面上的所有开发语">
<meta name="keywords" content="开发笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="WebApi集成JWT">
<meta property="og:url" content="https://tony_df.coding.net/2019/09/12/WebApi集成JWT/index.html">
<meta property="og:site_name" content="Tony&#39;s blog">
<meta property="og:description" content="终于聊回正事儿了，哈哈，今天聊聊jwt，概念性的东西，我还是不多说了，每个人肯定都有自己的认识，大家想深入了解的，自己去Google，去百度吧~咱们就直接看东西了先说一下jwt的官网：https://jwt.io/，集成开发的时候也是要到这里下载一下jwt的开发包，如果是.net 的话，建议直接用nuget包来管理；所谓jwt就是json web token的简称，所以，几乎支持市面上的所有开发语">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tony_df.coding.net/2019/09/12/WebApi集成JWT/nuget.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/09/12/WebApi集成JWT/jwt.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/09/12/WebApi集成JWT/makejwt.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/09/12/WebApi集成JWT/request.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/09/12/WebApi集成JWT/requesterr.png">
<meta property="og:updated_time" content="2019-09-12T05:16:33.861Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="WebApi集成JWT">
<meta name="twitter:description" content="终于聊回正事儿了，哈哈，今天聊聊jwt，概念性的东西，我还是不多说了，每个人肯定都有自己的认识，大家想深入了解的，自己去Google，去百度吧~咱们就直接看东西了先说一下jwt的官网：https://jwt.io/，集成开发的时候也是要到这里下载一下jwt的开发包，如果是.net 的话，建议直接用nuget包来管理；所谓jwt就是json web token的简称，所以，几乎支持市面上的所有开发语">
<meta name="twitter:image" content="https://tony_df.coding.net/2019/09/12/WebApi集成JWT/nuget.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/hexo/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Tony'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tony_df.coding.net/2019/09/12/WebApi集成JWT/">





  <title>WebApi集成JWT | Tony's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/hexo/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学着码代码,学着码人生;</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/hexo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/hexo/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/hexo/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tony_df.coding.net/hexo/2019/09/12/WebApi集成JWT/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/hexo/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">WebApi集成JWT</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-09-12T10:41:45+08:00">
                2019-09-12
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>终于聊回正事儿了，哈哈，今天聊聊jwt，概念性的东西，我还是不多说了，每个人肯定都有自己的认识，大家想深入了解的，自己去Google，去百度吧~<br>咱们就直接看东西了<br>先说一下jwt的官网：<a href="https://jwt.io/" target="_blank" rel="noopener">https://jwt.io/</a>，集成开发的时候也是要到这里下载一下jwt的开发包，如果是.net 的话，建议直接用nuget包来管理；<br><img src="nuget.png" alt="nuget"><br>所谓jwt就是json web token的简称，所以，几乎支持市面上的所有开发语言，.net ，当然不在话下了，对了虽然说不聊概念，但我还是想说一下为什么要用jwt，还记得我上篇举得那个喇叭裤的例子吗，jwt在接口安全性认证的层面，就是个宠儿和新贵的待遇，各大公司各大行业都纷纷追捧，所以为了让你的系统，或者是让你的知识能跟的上潮流，请选择jwt~<br>具体的优缺点就不提了，还是需要大家自行去百度，<br>来吧，看东西<br>之前我为两个小程序开发了后台接口，接口的安全性认证就是用的jwt，其实也是第一次接触，使用起来也不是很熟练，但配置完成后，会方便很多，许多访问安全上的问题，你在写接口的时候就不用再考虑了；<br>首先，根据jwt的数据结构，我简单截了个图<br><img src="jwt.png" alt="jwt结构"><br>简单来说就是，jwt通过特有的算法，将特定结构的数据，转换成一串字符串，那么这个特定的数据结构，包含header，payload，signature三个部分，如果我们的系统只是通过jwt来做安全性验证，那我们不用去研究这三个部分具体的作用，明白他的结构就可以了，但当你用了一段时间之后，会发现，本身jwt就是可以传输数据的，我们可以再payload的部分定义自己需要传输的数据格式，以此来完成数据的传输，需要注意的是，要放在payload里的数据一定不能是重要的身份信息等关键数据，要保证安全性；<br>看一下代码</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Response <span class="title">GetToken</span>(<span class="params">[FromBody] AuthModel authModel</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    Response resp = <span class="keyword">new</span> Response() &#123; code = <span class="number">-1</span>, message = <span class="string">"failed"</span> &#125;;</span><br><span class="line">    <span class="keyword">if</span> (authModel.account == <span class="string">"2010490073"</span> &amp;&amp; authModel.pwd == <span class="string">"123456"</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        DateTime UTC = DateTime.Now;</span><br><span class="line">        <span class="keyword">var</span> payload = <span class="keyword">new</span> Dictionary&lt;<span class="keyword">string</span>, <span class="keyword">object</span>&gt;</span><br><span class="line">        &#123;</span><br><span class="line">            &#123;<span class="string">"sub"</span>,authModel.sub&#125;,<span class="comment">//访问来源</span></span><br><span class="line">            &#123;<span class="string">"jti"</span>,Guid.NewGuid().ToString() &#125;,<span class="comment">//JWT ID,JWT的唯一标识</span></span><br><span class="line">            &#123;<span class="string">"iat"</span>, ConvertDateTimeToInt(UTC) &#125;,<span class="comment">//JWT颁发的时间</span></span><br><span class="line">            &#123;<span class="string">"issuer"</span>,<span class="string">"tony"</span>&#125;,<span class="comment">//签发者</span></span><br><span class="line">            &#123;<span class="string">"audience"</span>, authModel.account&#125;,<span class="comment">//jwt的接收该方，非必须</span></span><br><span class="line">            &#123;<span class="string">"exp"</span>,ConvertDateTimeToInt(UTC.AddHours(authModel.expiresAbsoulute))&#125;,<span class="comment">//JWT生命周期，注意，该内容和上面的颁发时间，数据格为时间戳</span></span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">string</span> secret = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[<span class="string">"TokenSecret"</span>]);</span><br><span class="line">        <span class="keyword">string</span> token = <span class="string">""</span>;</span><br><span class="line">        <span class="keyword">if</span> (JwtHelper.EncryptToken(payload, secret, <span class="keyword">out</span> token))</span><br><span class="line">        &#123;</span><br><span class="line">            resp.code = <span class="number">1</span>;</span><br><span class="line">            resp.message = <span class="string">"success"</span>;</span><br><span class="line">            resp.data = token;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">    &#123;</span><br><span class="line">        resp.code = <span class="number">-1</span>;</span><br><span class="line">        resp.message = <span class="string">"密钥错误"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> resp;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//jwt的加密算法</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">bool</span> <span class="title">EncryptToken</span>(<span class="params">Dictionary&lt;<span class="keyword">string</span>, <span class="keyword">object</span>&gt; dic, <span class="keyword">string</span> secret, <span class="keyword">out</span> <span class="keyword">string</span> token</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">try</span></span><br><span class="line">    &#123;</span><br><span class="line">        IJwtAlgorithm algorithm = <span class="keyword">new</span> HMACSHA256Algorithm();</span><br><span class="line">        IJsonSerializer serializer = <span class="keyword">new</span> JsonNetSerializer();</span><br><span class="line">        IBase64UrlEncoder urlEncoder = <span class="keyword">new</span> JwtBase64UrlEncoder();</span><br><span class="line">        IJwtEncoder encoder = <span class="keyword">new</span> JwtEncoder(algorithm, serializer, urlEncoder);</span><br><span class="line">        token = encoder.Encode(dic, secret);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Exception ex)</span><br><span class="line">    &#123;</span><br><span class="line">        token = <span class="string">"error_"</span> + ex.Message;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>看到这段代码模型验证的账号和密码我现在是写死的，正常来说这个信息是存储起来的，这个信息是你要颁发给客户端的，作为验证请求合法性的依据，那么，访问者要保存好这个凭据信息，并将请求的凭据信息放在后端，尽量不要通过前端js直接访问，如果是前后端分离的项目，则可以用node做一个中间件，如果实在无法避免直接请求，则至少需要保证请求协议为https，以保证传输过程的数据安全，并定期更换凭据；<br>生成jwt的秘钥要保存在数据中心的服务端，需要做好保存，如有发现凭据泄露风险，及时更换；<br>看一下访问效果；<br><img src="makejwt.png" alt="获取token"><br>这样我们就获取到了请求数据接口的凭证，在请求接口的时候，需要将该凭证放到header或者url里也可以，我习惯放到header，<br>说到这，再聊一下以前传统的身份验证方式，以前我们是通过session来存储用户的登录信息，用户登录通过后，会返回sessionid到客户端，客户端会把这个sessionid存到cookie里，然后之后的每次请求都会带着这个id过来，从而完成身份验证，相信大家如果自己百度过jwt的优缺点相关内容的话，肯定会看到相关的介绍，我就在简单提一下，有了jwt这种机制以后，服务端的数据中心会是一种无状态的状态（表达有限），我再举个例子吧，就好比我们过安检，那种session，cookie的方式，就像是，你该过安检了，一进站，发现里面一堆安检的点，每个安检的门上都贴着个名字，比如张三，在A点安检，李四，在B点安检…，找了一圈没你的名字说明你账号输入有误，就是人和安检的地点得是一一对应的，这样问题是，站点就那么大点地方，一下子过安检的人多了，就承载不过来了，那么jwt这种方式呢，不用对应了，有一个统一的安检口，来安检的人呢，先把票拿出来验票，是这的票就可以进，不是就不能进，一下子站台的好的资源就释放出来了。我理解大概就是这个样子~~<br>前面我们写了怎么出票，接下来聊一下验票，<br>首先在后台接口要有一个统一的网关，或者过滤器，验证请求的合法性，看下代码</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> Response <span class="title">ValidateToken</span>(<span class="params"><span class="keyword">string</span> encryptToken</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    Response resp = <span class="keyword">new</span> Response() &#123; code = <span class="number">5000</span>, message = <span class="string">"failed"</span> &#125;;</span><br><span class="line">    <span class="keyword">string</span> secret = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[<span class="string">"TokenSecret"</span>]);</span><br><span class="line">    <span class="comment">//解析Token，验证签名</span></span><br><span class="line">    <span class="keyword">string</span> json = <span class="string">""</span>;</span><br><span class="line">    <span class="keyword">if</span> (!JwtHelper.DecryptToken(encryptToken, secret, <span class="keyword">out</span> json))</span><br><span class="line">    &#123;</span><br><span class="line">        resp.code = <span class="number">5001</span>;</span><br><span class="line">        resp.message = <span class="string">"验签失败"</span>;</span><br><span class="line">        <span class="keyword">return</span> resp;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//验证载荷信息</span></span><br><span class="line">    JwtModel jwtModel = <span class="keyword">new</span> JwtModel();</span><br><span class="line">    <span class="keyword">if</span> (!JwtHelper.DeserializeJsonToModel(json, <span class="keyword">out</span> jwtModel))</span><br><span class="line">    &#123;</span><br><span class="line">        resp.code = <span class="number">5002</span>;</span><br><span class="line">        resp.message = <span class="string">"序列化失败"</span>;</span><br><span class="line">        <span class="keyword">return</span> resp;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//判断Token的绝对过期时间</span></span><br><span class="line">    <span class="keyword">if</span> (ConvertStringToDateTime(jwtModel.exp) &gt; DateTime.Now)</span><br><span class="line">    &#123;</span><br><span class="line">        resp.code = <span class="number">1</span>;</span><br><span class="line">        resp.message = <span class="string">"success"</span>;</span><br><span class="line">        <span class="keyword">return</span> resp;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> resp;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//jwt的解密算法</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">bool</span> <span class="title">DecryptToken</span>(<span class="params"><span class="keyword">string</span> token, <span class="keyword">string</span> secret, <span class="keyword">out</span> <span class="keyword">string</span> json_decode</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">try</span></span><br><span class="line">    &#123;</span><br><span class="line">        IJsonSerializer serializer = <span class="keyword">new</span> JsonNetSerializer();</span><br><span class="line">        IDateTimeProvider provider = <span class="keyword">new</span> UtcDateTimeProvider();</span><br><span class="line">        IJwtValidator validator = <span class="keyword">new</span> JwtValidator(serializer, provider);</span><br><span class="line">        IBase64UrlEncoder urlEncoder = <span class="keyword">new</span> JwtBase64UrlEncoder();</span><br><span class="line">        IJwtDecoder decoder = <span class="keyword">new</span> JwtDecoder(serializer, validator, urlEncoder);</span><br><span class="line">        json_decode = decoder.Decode(token, secret, verify: <span class="literal">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (Exception ex)</span><br><span class="line">    &#123;</span><br><span class="line">        json_decode = <span class="string">"error_"</span> + ex.Message;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后我们重载接口请求的入口方法</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">protected</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">Initialize</span>(<span class="params">HttpControllerContext controllerContext</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">base</span>.Initialize(controllerContext);</span><br><span class="line">    <span class="keyword">var</span> request = HttpContext.Current.Request;</span><br><span class="line">    <span class="comment">//获取请求头信息</span></span><br><span class="line">    <span class="keyword">var</span> requestHeader = request.Headers;</span><br><span class="line">    LogHelper.WriteLog(request.UserHostAddress + <span class="string">":"</span> + request.Url.AbsoluteUri);</span><br><span class="line">    <span class="comment">//获取token</span></span><br><span class="line">    <span class="keyword">var</span> token = requestHeader.Get(<span class="string">"token"</span>);</span><br><span class="line">    Response _resp = <span class="keyword">new</span> Response();</span><br><span class="line">    _resp = ValidateToken(token);</span><br><span class="line">    <span class="keyword">if</span> (_resp.code != <span class="number">1</span>)<span class="comment">//验证不通过</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">var</span> resp = <span class="keyword">new</span> System.Net.Http.HttpResponseMessage &#123; Content = <span class="keyword">new</span> System.Net.Http.StringContent(JsonConvert.SerializeObject(_resp), System.Text.Encoding.UTF8, <span class="string">"application/json"</span>) &#125;;<span class="comment">//返回内容不带转义字符</span></span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> HttpResponseException(resp);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//验证通过，放行</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样就基本完成了接口的安全性校验，再来看一下请求效果<br><img src="request.png" alt="接口请求"><br>如果去掉签名，或者签名错误，则会无法获取数据<br><img src="requesterr.png" alt="接口请求"><br>至此，jwt的集成就基本完成了，后续如果有更深层次的需求，我们可以在进一步的优化和升级<br>这篇就到这了</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/hexo/tags/开发笔记/" rel="tag"># 开发笔记</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/hexo/2019/09/05/再聊聊技术选型的问题/" rel="next" title="再聊聊技术选型的问题">
                <i class="fa fa-chevron-left"></i> 再聊聊技术选型的问题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/hexo/2019/09/17/记录一次win10更新版本后IIS无法启动的解决办法/" rel="prev" title="记录一次win10更新版本后IIS无法启动的解决办法">
                记录一次win10更新版本后IIS无法启动的解决办法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5bbb2338b87602f0" async="async"></script>
</div>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zOTA1My8xNTU4MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description">学习总结</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/hexo/archives/">
              
                  <span class="site-state-item-count">58</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/hexo/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/hexo/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/hexo/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/hexo/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/hexo/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/hexo/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/hexo/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

</body>
</html>
